package com.eduhzy.ttw.teacher.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.adapter.HomeFragmentAdapter;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.EntriesDetailData;
import com.eduhzy.ttw.commonsdk.utils.Utils;
import com.eduhzy.ttw.teacher.R;
import com.eduhzy.ttw.teacher.app.utils.RxUtils;
import com.eduhzy.ttw.teacher.di.component.DaggerSetUpComponent;
import com.eduhzy.ttw.teacher.mvp.contract.SetUpContract;
import com.eduhzy.ttw.teacher.mvp.presenter.SetUpPresenter;
import com.eduhzy.ttw.teacher.mvp.ui.fragment.DiscoverFragment;
import com.eduhzy.ttw.teacher.mvp.ui.fragment.HomeFragment;
import com.eduhzy.ttw.teacher.mvp.ui.fragment.MineFragment;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.AppManager;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.umeng.analytics.MobclickAgent;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zyyoona7.popup.EasyPopup;
import com.zyyoona7.popup.XGravity;
import com.zyyoona7.popup.YGravity;

import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import io.github.leibnik.wechatradiobar.WeChatRadioGroup;
import io.realm.Realm;
import io.realm.RealmConfiguration;

import static com.jess.arms.utils.Preconditions.checkNotNull;

@Route(path = RouterHub.APP_HOMEACTIVITY)
public class HomeActivity extends BaseActivity<SetUpPresenter> implements SetUpContract.View {
    private int REQUEST_CODE_SCAN = 111;

    @BindView(R.id.home_viewpager)
    ViewPager mViewpager;

    @BindView(R.id.home_radio_group)
    WeChatRadioGroup homeRadioGroup;
    //    String[] tabs = {"首页", "通讯录", "发现", "我"};
    String[] tabs = {"首页", "发现", "我"};
    List<Fragment> mFragments;


    @BindView(R.id.public_toolbar_title_home)
    TextView mTitle;
    @BindView(R.id.public_toolbar_right_iv_layout)
    AutoRelativeLayout publicToolbarAdd;
    @BindView(R.id.public_toolbar_search)
    AutoRelativeLayout mSearch;
    @BindView(R.id.home_toolbar)
    AutoRelativeLayout mToolbar;
    @BindView(R.id.public_iv_avatar)
    QMUIRadiusImageView ivAvatar;
    @BindView(R.id.public_tv_level)
    TextView tvLevel;
    @Inject
    AppManager mAppManager;

    private String nickname;
    private EasyPopup addPop;
    private ViewHolder vh;
    private long exitTime;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerSetUpComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
        MobclickAgent.onEvent(getActivity(), "ttw_home");
        return R.layout.activity_home;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter.getAppUpdate();
        mSearch.setVisibility(View.GONE);
        nickname = SPUtils.getInstance().getString(Constants.USERNICKNAME);
        initFistPageData();
        mFragments = new ArrayList<>();
        mFragments.add(HomeFragment.newInstance());
//        mFragments.add(ContactFragment.newInstance());
        mFragments.add(DiscoverFragment.newInstance());
        mFragments.add(MineFragment.newInstance());
        initViewPager();
        initJPush();
        initDB();
    }

    private void initDB() {
        if (ObjectUtils.isNotEmpty(SPUtils.getInstance().getString(Constants.USERID))) {
            String userId = SPUtils.getInstance().getString(Constants.USERID);
            RealmConfiguration config = new RealmConfiguration.Builder()
                    .name("Realm" + userId + ".realm")
                    .deleteRealmIfMigrationNeeded()
                    .build();
            Realm.setDefaultConfiguration(config);
        } else {
            showMessage("数据库初使化失败");
            return;
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (JPushInterface.isPushStopped(getActivity())) {
            JPushInterface.resumePush(getActivity());//恢复极光推送
        }
    }

    private void initJPush() {
        JPushInterface.setAlias(getActivity(), 2, Constants.JPushAlias + SPUtils.getInstance().getString(Constants.USERID));

    }

    private void initViewPager() {
        HomeFragmentAdapter adapter = new HomeFragmentAdapter(getSupportFragmentManager(), Arrays.asList(tabs), mFragments);
        mViewpager.setAdapter(adapter);
        mViewpager.setOffscreenPageLimit(4);
        // 关键代码
        homeRadioGroup.setViewPager(mViewpager);
        mViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    initFistPageData();
                } else {
                    tvLevel.setVisibility(View.GONE);
                    ivAvatar.setVisibility(View.GONE);
                    mTitle.setText("堂堂网");
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initFistPageData() {
        ivAvatar.setVisibility(View.VISIBLE);
        tvLevel.setVisibility(View.GONE);
        mToolbar.setVisibility(View.VISIBLE);
        mTitle.setText(nickname);
        Glide.with(getActivity())
                .load(SPUtils.getInstance().getString(Constants.TEMPAVATAR))
                .apply(RequestOptions.placeholderOf(R.drawable.img_touxiang).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL))
                .into(ivAvatar);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        RxUtil.showTipDialog(this, QMUITipDialog.Builder.ICON_TYPE_NOTHING, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    @OnClick({R.id.public_toolbar_right_iv_layout, R.id.public_toolbar_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.public_toolbar_right_iv_layout:
                initAddPop();
                ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) ((ViewGroup) view).getChildAt(0).getLayoutParams();
                int rightMargin = layoutParams.rightMargin;
                addPop.showAtAnchorView(view, YGravity.BELOW, XGravity.ALIGN_RIGHT, -rightMargin, -rightMargin);
                break;
            case R.id.public_toolbar_search:
                break;
            default:
        }
    }

    private void initAddPop() {
        if (addPop == null) {
            addPop = EasyPopup.create()
                    .setContext(this)
                    .setContentView(R.layout.popup_layout_home_add)
                    .setOnViewListener((view, easyPopup) -> {
                        if (vh == null) {
                            vh = new ViewHolder(view);
                        }
                    })
//                .setAnimationStyle(R.style.RightTop2PopAnim)
                    //是否允许点击PopupWindow之外的地方消失
                    .setFocusAndOutsideEnable(true)
                    //允许背景变暗
                    .setBackgroundDimEnable(true)
                    //变暗的透明度(0-1)，0为完全透明
                    .setDimValue(0.5f)
                    //变暗的背景颜色
//                .setDimColor(Color.RED)
                    //指定任意 ViewGroup 背景变暗
//                .setDimView(mTitleBar)
                    .apply();
        }
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Subscriber(tag = RouterHub.APP_HOMEACTIVITY)
    public void onEvents(Message msg) {
        switch (msg.what) {
            case EventBusTags.SCANER_CODE_SUCCESS:
                String code = (String) msg.obj;
                if (code.startsWith(Constants.QRCODE_PREFIX_TYPE.CLASS)) {
                    ARouter.getInstance().build(RouterHub.APP_CLASSDETAILSACTIVITY)
                            .withString(Intent.EXTRA_TITLE, Constants.CLASS_DETAILS)
                            .withString(Constants.ROUTER_STRING, code)
                            .withBoolean(Constants.ROUTER_BOOLEAN, true)
                            .navigation();
                } else if (code.startsWith(Constants.QRCODE_PREFIX_TYPE.USER)) {
                    ARouter.getInstance().build(RouterHub.APP_CONTACTDETAILSACTIVITY)
                            .withString(Intent.EXTRA_TITLE, Constants.CONTACT_DETAILS)
                            .withString(Constants.ROUTER_STRING, code)
                            .navigation();
                }
                break;
            case EventBusTags.PERSON_UPDATE_SUCCESS:
                nickname = (String) msg.obj;
                break;
            case EventBusTags.UPDATE_AVATAR:
                String avatar = (String) msg.obj;
                Glide.with(getActivity())
                        .load(avatar)
                        .apply(RequestOptions.placeholderOf(R.drawable.img_touxiang).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL))
                        .into(ivAvatar);
                break;
            case EventBusTags.SHOW_SHARE:
                if (ObjectUtils.isNotEmpty(msg.obj)) {
                    EntriesDetailData data = (EntriesDetailData) msg.obj;
                    RxUtils.showShareURLMenu(mAppManager.getTopActivity(), data.getShareLink(), data.getWorksName(), data.getUnionName() + " (" + data.getUnionUnit() + ")", ObjectUtils.isNotEmpty(data.getAttachmentList())?data.getAttachmentList().get(0).getPreviewAddr():null);
                }
                break;
            default:
        }
    }

    class ViewHolder {
        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }

        @OnClick({R.id.tv_create_class, R.id.tv_join_class, R.id.tv_create_group, R.id.tv_add_friend, R.id.tv_scan})
        public void onPopupClicked(View view) {
            addPop.dismiss();
            switch (view.getId()) {
                case R.id.tv_create_class:
                    Utils.navigationWithTitle(RouterHub.APP_CREATECLASSACTIVITY, Constants.CREATE_CLASS);
                    break;
                case R.id.tv_join_class:
                    ARouter.getInstance().build(RouterHub.APP_JOINCLASSACTIVITY)
                            .withString(Intent.EXTRA_TITLE, Constants.JOIN_CLASS)
                            .navigation();
                    break;
                case R.id.tv_create_group:
                    break;
                case R.id.tv_add_friend:
                    ARouter.getInstance().build(RouterHub.APP_JOINCLASSACTIVITY)
                            .withString(Intent.EXTRA_TITLE, Constants.ADD_FRIEND)
                            .navigation();
                    break;
                case R.id.tv_scan:
                    Intent intent = new Intent(getActivity(), CaptureActivity.class);
                    ZxingConfig config = new ZxingConfig();
                    config.setPlayBeep(true);//是否播放扫描声音 默认为true
                    config.setShake(true);//是否震动  默认为true
                    config.setDecodeBarCode(false);//是否扫描条形码 默认为true
                    config.setReactColor(R.color.white);//设置扫描框四个角的颜色 默认为淡蓝色
                    config.setFrameLineColor(R.color.white);//设置扫描框边框颜色 默认无色
                    config.setFullScreenScan(false);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描
                    intent.putExtra(com.yzq.zxinglibrary.common.Constant.INTENT_ZXING_CONFIG, config);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
//                    ARouter.getInstance().build(RouterHub.RXFEATURE_ACTIVITYSCANERCODE)
//                            .withString(Intent.EXTRA_TITLE, Constants.SCANER_QRCODE)
//                            .withString(Constants.ROUTER_DATA, RouterHub.APP_HOMEACTIVITY)
//                            .navigation(getActivity());
                    break;
                default:
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mFragments.get(mViewpager.getCurrentItem()).onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String code = data.getStringExtra(Constant.CODED_CONTENT);
                if (code.startsWith(Constants.QRCODE_PREFIX_TYPE.CLASS)) {
                    ARouter.getInstance().build(RouterHub.APP_CLASSDETAILSACTIVITY)
                            .withString(Intent.EXTRA_TITLE, Constants.CLASS_DETAILS)
                            .withString(Constants.ROUTER_STRING, code)
                            .withBoolean(Constants.ROUTER_BOOLEAN, true)
                            .navigation();
                } else if (code.startsWith(Constants.QRCODE_PREFIX_TYPE.USER)) {
                    ARouter.getInstance().build(RouterHub.APP_CONTACTDETAILSACTIVITY)
                            .withString(Intent.EXTRA_TITLE, Constants.CONTACT_DETAILS)
                            .withString(Constants.ROUTER_STRING, code)
                            .navigation();
                }
            }
        }
    }


}
